<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        type="index"
        width="50"
        align="center"
      />
      <el-table-column label="用户名" prop="account" sortable="custom" align="center">
        <template slot-scope="{row}">
          <span>{{ row.account }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="email" align="center">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色">
        <template slot-scope="{row}">
          <span>{{ row.role_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ adminStatus[row.status]['display_name'] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button v-waves size="small" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status==0" v-waves size="small" @click="changeStatus(row.id, 4)">
            启用
          </el-button>
          <el-button v-if="row.status==1" v-waves size="small" type="danger" @click="changeStatus(row.id, 3)">
            禁用
          </el-button>
          <el-button v-waves size="small" @click="changeStatus(row.id, 5)">
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户名" prop="account">
          <el-input v-model="temp.account" />
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select v-model="temp.role_id" clearable class="filter-item" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="email" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in adminStatus" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='add'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { adminStatus } from '@/utils/dataType'
import { fetchList, fetchChangeStatus, fetchAdd, fetchEdit } from '@/api/admins'
import { fetchList as fetchRoleList } from '@/api/roles'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'Admin',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = ['success', 'danger']
      return statusMap[status]
    },
    dateFormat(time) {
      return parseTime(time, '{y}-{m}-{d} {h}:{i}')
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      roleList: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        search: undefined,
        status: undefined,
        order: '-id'
      },
      adminStatus,
      loading: {
        stop: false,
        reset: false,
        cancel: false
      },
      temp: {
        id: undefined,
        account: undefined, 
        phone: undefined,
        email: undefined,
        role_id: undefined,
        role_name: undefined,
        status: 0
      },
      textMap: {
        add: '新增',
        edit: '修改'
      },
      rules: {
        phone: [{ required: true, message: '手机号必须填写', trigger: 'blur' }],
        role_id: [{ required: true, message: '角色必须选择', trigger: 'change' }],
        account: [{ required: true, message: '用户名必须填写', trigger: 'blur' }]
      },
      dialogStatus: undefined,
      dialogFormVisible: false,
      downloadLoading: false
    }
  },
  created() {
    this.getRoleList()
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      const { data: { list, total }} = await fetchList(this.listQuery)
      this.list = list
      this.total = total
      this.listLoading = false
    },
    async getRoleList() {
      const { data } = await fetchRoleList()
      this.roleList = data
    },
    async changeStatus(id, type) {
      await fetchChangeStatus({ id, type })
      Message.success('修改成功')
    },
    parseTime,
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.order = '-id'
      } else {
        this.listQuery.order = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      Object.assign(this.$data.temp, this.$options.data().temp)
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchAdd(this.temp).then(_=> Message.success('新增成功'))
        }
      })
    },
    handleUpdate(row) {
      this.temp = { ...row }
      this.dialogStatus = 'edit'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchEdit(this.temp).then(_=> {
            this.dialogFormVisible = false
            Message.success('修改成功')
          })
          //   this.$notify({
          //     title: 'Success',
          //     message: 'Update Successfully',
          //     type: 'success',
          //     duration: 2000
          //   })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['account', 'phone', 'email', 'role_name', 'status']
        excel.export_json_to_excel({
          header: tHeader,
          data: this.list,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    }
  }
}
</script>
